# -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcplugin, xbmcaddon, urllib2, urllib, re, string, sys, os, qqlive

# QQLive.COM(腾讯视频) by Yang SUn, 2011

# Plugin constants 
__addonname__ = "腾讯视频"
__addonid__ = "plugin.video.qqlive"
__addon__ = xbmcaddon.Addon(id=__addonid__)

ACT_MOVIE_LIST = '1'
ACT_CHANGE_CHANNEL = '2'

def get_params(param_string):
    param = []
    paramstring = param_string
    if len(paramstring) >= 2:
        params = param_string
        cleanedparams = params.replace('?', '')
        if (params[len(params) - 1] == '/'):
            params = params[0:len(params) - 2]
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]   
    return param

def rootList():
    totalLen = len(qqlive.CHANNEL)
    index = 1 
    for key in qqlive.CHANNEL.keys():
        li = xbmcgui.ListItem(str(index) + '. ' + key)
        u = sys.argv[0] + '?action=1&url=' + urllib.quote_plus(qqlive.CHANNEL[key])
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True, totalLen)
        index = index + 1
    xbmcplugin.setContent(int(sys.argv[1]), 'channels')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
    return

def movieList(url):
    dialog = xbmcgui.Dialog()
    #dialog.ok('DEBUG', url)
    movie_type = __addon__.getSetting('movie_type')
    movie_area = __addon__.getSetting('movie_area')
    movie_year = __addon__.getSetting('movie_year')
    videos = qqlive.getVideos(url)
    totalLen = len(videos) + 1
    
    li = xbmcgui.ListItem('按类型[COLOR FFFF0000]【' + movie_type + '】[/COLOR]按地区[COLOR FFFF0000]【' + movie_area + '】[/COLOR]按年份[COLOR FFFF0000]【' + movie_year + '】[/COLOR]（按此选择）')
    u = sys.argv[0] + '?action=2'
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, False, 1)
    
    for video in videos:
        li = xbmcgui.ListItem(label = video.title, thumbnailImage = video.img)
        u = sys.argv[0] + "?action=2&url=" + urllib.quote_plus(video.link)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True, totalLen)
        
    xbmcplugin.setContent(int(sys.argv[1]), 'videos')    
    xbmcplugin.endOfDirectory(int(sys.argv[1]))  
    return

def changeChannel():
    dialog = xbmcgui.Dialog()
    list = [channel for channel in qqlive.CHANNEL.keys()]
    sel = dialog.select('节目分类', list)
    if sel != -1:
        __addon__.setSetting(id="mi_channel", value=list[sel])
    xbmc.executebuiltin('Container.Refresh')

def contentList():
    mi_channel = __addon__.getSetting('mi_channel')
    mi_type = __addon__.getSetting('mi_type')
    mi_area = __addon__.getSetting('mi_area')
    mi_year = __addon__.getSetting('mi_year')
    
    totalItems = 1
    li = xbmcgui.ListItem('节目分类[COLOR FF00FF00]【' + mi_channel + '】[/COLOR]（按此选择）')
    u = sys.argv[0] + '?action=' + ACT_CHANGE_CHANNEL
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, False, totalItems)
    xbmcplugin.setContent(int(sys.argv[1]), 'videos')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
    return

params = get_params(sys.argv[2])

action = None
name = None
url = None
thumb = None
page = None

try:
    action = urllib.unquote_plus(params["action"])
except:
    pass
try:
    url = urllib.unquote_plus(params["url"])
except:
    pass

if action == None:
    contentList()
    #rootList()
elif action == ACT_CHANGE_CHANNEL:
    changeChannel()
    #movieList(url);
    
#url='http://vhotwsh.video.qq.com/flv/61/201/7XfcrDpMIsb.mp4?vkey=19C2BDE27FF060518B2D2B14E567E2134A02DFB9B5419BA761852121D8413978&sdtfrom=v2&type=mp4'
#xbmc.Player().play(url)


